package com.manfred.nio.NIOStudy;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class App {
	public static void main(String[] args) throws Exception {

		// RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt",
		// "rw"); FileChannel inChannel = aFile.getChannel();
		//
		// ByteBuffer buf = ByteBuffer.allocate(48); List<Byte> bytes = new
		// ArrayList<Byte>(); int bytesRead = inChannel.read(buf); while
		// (bytesRead != -1) { System.out.println("Read " + bytesRead);
		// buf.flip();
		//
		// while (buf.hasRemaining()) { byte b = buf.get();
		// System.out.print((char) b); bytes.add(b); }
		//
		// buf.clear(); bytesRead = inChannel.read(buf); } aFile.close(); byte[]
		// b = new byte[bytes.size()]; for (int i = 0; i < bytes.size(); i ++) {
		// b[i] = bytes.get(i); } System.out.println(new String(b));

		// RandomAccessFile fromFile = new RandomAccessFile("data/nio-data.txt",
		// "rw");
		// FileChannel fromChannel = fromFile.getChannel();
		// RandomAccessFile toFile = new RandomAccessFile("data/toFile.txt",
		// "rw");
		// FileChannel toChannel = toFile.getChannel();
		// long position = 0;
		// long count = fromChannel.size();
		// toChannel.transferFrom(fromChannel, position, count);

		RandomAccessFile fromFile = new RandomAccessFile("data/nio-data.txt",
				"rw");
		FileChannel channel = fromFile.getChannel();
		
		channel.position(channel.size());
//		channel.position(channel.size()+1000000); // 文件空洞
		
		String newData = "New String to write to file..."
				+ System.currentTimeMillis();

		ByteBuffer buf = ByteBuffer.allocate(48);
		buf.clear();
		buf.put(newData.getBytes());

		buf.flip();

		while (buf.hasRemaining()) {
			channel.write(buf);
		}
		channel.truncate(1024);

		channel.close();
	}
}
